import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import '../../base/MyScaffold.dart';
import '../../model/Set.dart';
import '../dialog/Add.dart';
import '../loginregister/Login.dart';
import '../../utils/EventBus/EventBus.dart';
import '../../model/Bus.dart';
import '../../utils/Toast/MyTosat.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';
import 'package:launch_review/launch_review.dart';
import 'package:sp_util/sp_util.dart';

import '../../config/Constant.dart';
import '../../login/Controller/LoginController.dart';
import '../../model/Process.dart';
import '../../res.dart';
import '../../utils/Toast/Tosat.dart';
import '../../utils/cache/CacheUtils.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/userbloc/user_bloc.dart';
import '../../widgets/MyImage.dart';
import '../../widgets/MyLocalImage.dart';
import '../about/AboutUs.dart';
import '../feedback/Feedback.dart';
import '../laguage/Laguage.dart';
import '../process/Processing.dart';
import '../subscribe/Subscribe.dart';
import 'FileHome.dart';
import 'Tool.dart';

class HomeTabBar extends StatefulWidget {
  const HomeTabBar({Key? key}) : super(key: key);

  @override
  State<HomeTabBar> createState() => _HomeTabBarState();
}

class _HomeTabBarState extends State<HomeTabBar> {
  late File file;
  StreamSubscription? subscription;
  final Controller controller = Get.put(Controller());
  String cacheStr = "0M";
  List<Map> tabbars = [
    {
      'title': 'file'.tr,
      'imgPath': Res.tab_icon_file_nor,
      'selectedImgPath': Res.tab_icon_file_sel,
      'w': 27.0,
      'h': 27.0,
    },
    {
      'title': '',
      'imgPath': Res.icon_tabbar_plus,
      'selectedImgPath': Res.icon_tabbar_plus,
      'w': 48.0,
      'h': 32.0,
    },
    {
      'title': 'tool'.tr,
      'imgPath': Res.tab_icon_tool_nor,
      'selectedImgPath': Res.tab_icon_tool_sel,
      'w': 27.0,
      'h': 27.0
    },
  ];
  int _curIndex = 0;
  List<BottomNavigationBarItem> _tabbarItems = [];

  int postion = 0;

  // ignore: non_constant_identifier_names
  BottomNavigationBarItem TabBarItem(
      {required String label,
      required String imgPath,
      required String selectedImgPath,
      required Size size}) {
    return BottomNavigationBarItem(
        label: label,
        icon: Container(
            padding: const EdgeInsets.only(bottom: 2),
            child:
                MyLocalImage(imgPath, width: size.width, height: size.height)),
        activeIcon: Container(
          padding: const EdgeInsets.only(bottom: 2),
          child: MyLocalImage(selectedImgPath,
              width: size.width, height: size.height),
        ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller.Info();

    SpUtil.putString(Constant.first, "1111111");


    tabbars.forEach((map) {
      _tabbarItems.add(TabBarItem(
          label: map['title'],
          imgPath: map['imgPath'],
          selectedImgPath: map['selectedImgPath'],
          size: Size(map['w'] as double, map['h'] as double)));
    });
    subscription = EventBusUtil.addListener<Bus>((event) {
      if (event.label == Constant.CONVERT_MSG) {
        Process process = event.data as Process;
        print(process.toString());
        toast(process);
      } else if (event.label == Constant.ADD_FILE_MSG) {
        setState(() {
          _curIndex = 0;
        });
      } else if (event.label == Constant.USER_INFORMATION_UPDATE) {
        setState(() {});
        // var lang = SpUtil.getString(Constant.lanuage);
        // var code = SpUtil.getString(Constant.code);
        // if (lang != null) {
        //   var locale = Locale(lang!, code);
        //   Get.updateLocale(locale);
        // }

      }
    });

    //calCacheTotal();
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      navBarHide: true,
      drawer: getDrawer(),
      body: IndexedStack(
        index: _curIndex,
        children: const [
          FileHome(),
          Tool(),
          Tool(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
          unselectedItemColor: rgba(200, 202, 204, 1),
          unselectedFontSize: 10,
          selectedItemColor: rgba(255, 78, 77, 1),
          selectedFontSize: 10,
          elevation: 1,
          backgroundColor: Colors.white,
          type: BottomNavigationBarType.fixed,
          onTap: (index) {
            setState(() {
              if (index == 1) {
                // _selectFile();
                Get.bottomSheet(const AddDialog());
              } else {
                _curIndex = index;
              }
            });
          },
          currentIndex: _curIndex,
          items: _tabbarItems),
    );
  }

  ///计算缓存大小
  Future<void> calCacheTotal() async {
    int size = await CacheUtils.total();
    double si = size / 1024 / 1024.0;
    cacheStr = "${si.toStringAsFixed(1)}M";
    if (mounted) {
      setState(() {});
    }
  }

  ///计算缓存大小
  Future<void> clear() async {
    await CacheUtils.clear();
    calCacheTotal();
  }

  Widget getDrawer() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 64),
      alignment: Alignment.centerLeft,
      width: MediaQuery.of(context).size.width * 0.8,
      child: Column(
        children: [
          InkWell(
            onTap: () {
              if (!UserBlocTool.isLogin()) {
                Get.to(const Login());
              }
            },
            child: Container(
              margin: const EdgeInsets.all(16),
              alignment: Alignment.center,
              child: Row(
                children: [
                  MyImage(
                    UserBlocTool.isLogin()
                        ? UserBlocTool.getUser()!.avatar
                        : Res.sys_icon_logo,
                    width: 56,
                    height: 56,
                    radius: UserBlocTool.isLogin() ? 28 : 0,
                  ),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: TextView(
                                UserBlocTool.isLogin()
                                    ? UserBlocTool.getUser()!.nickname
                                    : "login".tr,
                                overflow: TextOverflow.ellipsis,
                                margin:
                                    const EdgeInsets.symmetric(horizontal: 10),
                                style: TextStyle(
                                    color: ColorUtils.text,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            if (UserBlocTool.getUser()?.is_vip == "1" &&
                                UserBlocTool.isLogin())
                              const MyImage(
                                Res.sidebar_pro,
                                width: 30,
                                height: 18,
                              )
                          ],
                        ),
                        if (UserBlocTool.isLogin())
                          TextView(
                            UserBlocTool.getUser()!.nickname,
                            margin: const EdgeInsets.only(left: 10, top: 5),
                            style: TextStyle(
                                color: ColorUtils.text_, fontSize: 14),
                          ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          Divider(
            thickness: 0.5,
            color: rgba(230, 231, 235, 1),
          ),
          getItemDrawer(Settings(
              name: "language".tr,
              icon: Res.sidebar_icon_language,
              onclick: () {
                Get.to(const Laguage());
              },
              tips: SpUtil.getString(Constant.cname)!)),
          getItemDrawer(Settings(
              name: "issue".tr,
              icon: Res.sidebar_icon_report,
              onclick: () {
                Get.to(const MyFeedback());
              })),
          // getItemDrawer(Settings(
          //     name: "cache".tr,
          //     icon: Res.sidebar_icon_clear,
          //     onclick: () async {
          //       /// 更新缓存
          //       await clear();
          //     },
          //     tips: cacheStr)),
          Divider(
            thickness: 0.5,
            color: rgba(230, 231, 235, 1),
          ),
          getItemDrawer(
            Settings(
                name: "pro".tr,
                icon: Res.sidebar_icon_pro,
                vip: true,
                onclick: () {
                  if (UserBlocTool.getUser()?.is_vip == "0" ||
                      !UserBlocTool.isLogin()) {
                    Get.to(const Subscribe());
                  }
                }),
          ),
          getItemDrawer(Settings(
              name: "editor".tr,
              icon: Res.sidebar_icon_rata,
              onclick: () {
                alertAddProduct();
              })),
          getItemDrawer(Settings(
              name: "about".tr,
              icon: Res.sidebar_icon_privacy,
              onclick: () {
                Get.to(const AboutUs());
              })),
          Divider(
            thickness: 0.5,
            color: rgba(230, 231, 235, 1),
          ),
          getItemDrawer(Settings(
              name: UserBlocTool.isLogin() ? "out".tr : "login".tr,
              icon: Res.sidebar_icon_login,
              onclick: () {
                if (UserBlocTool.isLogin()) {
                  UserBlocTool.exit();
                  setState(() {});
                }
                Get.to(const Login());
              })),
        ],
      ),
    );
  }

  Widget getItemDrawer(Settings settings) {
    return InkWell(
      onTap: settings.onclick,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
            child: Row(
              children: [
                MyLocalImage(
                  settings.icon,
                  width: 24,
                  height: 24,
                ),
                Expanded(
                  child: TextView(
                    settings.name,
                    style: TextStyle(color: ColorUtils.text, fontSize: 16),
                    margin: const EdgeInsets.symmetric(horizontal: 16),
                  ),
                ),
                if (settings.tips.isNotEmpty)
                  TextView(
                    settings.tips,
                    style:
                        TextStyle(color: rgba(150, 151, 153, 1), fontSize: 12),
                  ),
                if (settings.vip)
                  MyLocalImage(
                    UserBlocTool.isLogin() &&
                            UserBlocTool.userEntity!.is_vip == "1"
                        ? Res.sidebar_icon_switch_open
                        : Res.sidebar_icon_switch_close,
                    width: 48,
                    height: 26,
                  )
              ],
            ),
          ),
        ],
      ),
    );
  }

  alertAddProduct() {
    Get.defaultDialog(
      radius: 10,
      title: "rate_us".tr,
      contentPadding: const EdgeInsets.only(top: 12, bottom: 12),
      titlePadding: const EdgeInsets.only(top: 20),
      content: Container(
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: [
            TextView(
              "valuable".tr,
              style: TextStyle(color: ColorUtils.text_),
            ),
            Container(
              height: 60,
              margin: const EdgeInsets.only(top: 20),
              padding: const EdgeInsets.symmetric(horizontal: 40),
              child: GridView.builder(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    //设置列数
                    crossAxisCount: 5,
                    //设置横向间距
                    crossAxisSpacing: 10,
                    //设置主轴间距
                    mainAxisSpacing: 10,
                  ),
                  physics: const NeverScrollableScrollPhysics(),
                  //是否允许内容适配           非常非常非常非常重要
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  itemCount: 5,
                  itemBuilder: (context, index) {
                    return Container(
                        child: Obx(
                      () => MyLocalImage(
                        index >= controller.postion.value
                            ? Res.sys_icon_rating_nor
                            : Res.sys_icon_rating_sel,
                        width: 30,
                        height: 30,
                        onclick: () {

                          if (index == 4) {
                            MyToast().show("great".tr);
                            LaunchReview.launch(
                                androidAppId: "com.pdfeditor.apps",
                                writeReview: true);
                          } else {
                            MyToast().show("evaluation".tr);
                          }
                          print(index);
                          controller.setPostion(index + 1);
                          Get.back();
                        },
                      ),
                    ));
                  }),
            )
          ],
        ),
      ),
    );
  }

  getState(int state) {
    if (state == 0) {
      return "processing".tr;
    } else if (state == 1) {
      return "success".tr;
    } else {
      return "fail".tr;
    }
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
    print("使不活动");
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    EventBusUtil.removeListener(subscription!);
    print("拥有");
  }

  void toast(Process process) {
    String Path;
    Color color;
    if (process.state == 0) {
      Path = Res.sys_icon_tips_convertpdf;
      color = rgba(0, 132, 255, 1);
    } else if (process.state == 1) {
      Path = Res.sys_icon_tips_success;
      color = rgba(0, 180, 75, 1);
    } else {
      Path = Res.sys_icon_tips_fail;
      color = rgba(255, 0, 14, 1);
    }
    ToastSingleton.getInstance(context).showToast(
      child: Container(
        height: 68,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
            color: rgba(34, 34, 34, 1), borderRadius: BorderRadius.circular(6)),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          children: [
            MyLocalImage(
              Path,
              width: 16,
              height: 16,
            ),
            Expanded(
              child: Container(
                alignment: Alignment.centerLeft,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextView(
                      process.name,
                      margin: const EdgeInsets.only(left: 10),
                      alignment: Alignment.centerLeft,
                      textAlign: TextAlign.start,
                      style: const TextStyle(color: Colors.white),
                    ),
                    TextView(
                      process.type + " " + getState(process.state),
                      margin: const EdgeInsets.only(left: 10, top: 4),
                      textAlign: TextAlign.start,
                      alignment: Alignment.centerLeft,
                      style: const TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
            TextView(
              process.state == 1 ? "open".tr : "check".tr,
              width: 62,
              height: 30,
              backcolor: color,
              alignment: Alignment.center,
              style: const TextStyle(color: Colors.white),
              radius: BorderRadius.circular(4),
              onclick: () {
                Get.to(const Processing());
              },
            )
          ],
        ),
      ),
      // gravity: ToastGravity.BOTTOM,
      positionedToastBuilder: (context, child) {
        return Positioned(
          left: 19.0,
          right: 19.0,
          bottom: 100,
          child: child,
        );
      },
      fadeDuration: const Duration(milliseconds: 500),
      toastDuration: const Duration(seconds: 3),
    );
  }
}
